/**
 * Created with IntelliJ IDEA.
 * Description:获取链表中间节点
 * User: dings
 * Date: 2024-07-08
 * Time: 15:00
 */
class ListNode {
      int val;
      ListNode next;
      ListNode() {

      }
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }
public class Test {
    public ListNode middleNode(ListNode head) {
        //快慢指针法求解
        ListNode slow = head;
        ListNode fast = head;

        //找中间节点
        //一定要fast != null在前，避免出现空指针异常
        //两个条件只要有一个不满足就结束循环，说明到了中间节点的位置
        while (fast != null && fast.next != null) {
            ListNode fastN = fast.next;
            fast = fastN.next;
            slow = slow.next;
        }

        //返回中间节点
        return slow;
    }
    public static void main(String[] args) {

    }
}
